package com.enjoyor.soa.traffic.util.base;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanMap;

public class BeanUtil {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> toMap(Object obj) {
        Map<String, Object> map = new HashMap();
        if (obj == null) {
            return map;
        }
        BeanMap beanMap = new BeanMap(obj);
        Iterator<String> it = beanMap.keyIterator();
        while (it.hasNext()) {
            String name = (String) it.next();
            Object value = beanMap.get(name);
            if ((value != null) && (!name.equals("class"))) {
                map.put(name, value);
            }
        }
        return map;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> toMap(Object... objs) {
        Map<String, Object> map = new HashMap();
        for (Object object : objs) {
            if (object != null) {
                map.putAll(toMap(object));
            }
        }
        return map;
    }

    @SuppressWarnings("rawtypes")
    public static Class<?> getGenericClass(Class<?> clazz) {
        Type t = clazz.getGenericSuperclass();
        if ((t instanceof ParameterizedType)) {
            Type[] p = ((ParameterizedType) t).getActualTypeArguments();
            return (Class) p[0];
        }
        return null;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<Object, Object> convertCollection2Map(Collection list, String keyName, String valueName) {
        Map<Object, Object> map = new HashMap();
        if ((list != null) && (list.size() > 0) && (keyName != null) && (!keyName.isEmpty())) {
            for (Object bean : list) {
                Object key = ReflectUtil.getFieldValue(bean, keyName);
                Object value = (valueName == null) || (valueName.isEmpty()) ? bean
                        : ReflectUtil.getFieldValue(bean, valueName);
                if (key != null) {
                    map.put(key, value);
                }
            }
        }
        return map;
    }

}
